using System;
using System.Collections.Generic;
using System.Text;
using AppExtensions.Views;
using System.Threading;
using AppExtensions.Exceptions;

namespace AppExtensions.Routing
{
    public static class Router
    {
        private static ReaderWriterLock lockRoutes = new ReaderWriterLock();

        private static Dictionary<string, Route> Routes = new Dictionary<string, Route>();
        
        public static void AddRoute<TView>(Route route)
        {
            lockRoutes.AcquireWriterLock(0);
            Routes.Add(typeof(TView).FullName, route);
            lockRoutes.ReleaseWriterLock();
        }

        private static Route GetRoute<TView>()
        {
            string viewName = typeof(TView).FullName;
            if (Routes.ContainsKey(viewName))
                return Routes[viewName];
            else
                return null;
        }

        public static void RemoveRoute<TView>(Route route)
        {
            lockRoutes.AcquireWriterLock(0);
            Routes.Remove(typeof(TView).FullName);
            lockRoutes.ReleaseWriterLock();
        }

        public static void RedirectTo<TView>() where TView : IBaseView
        {
            Route route = GetRoute<TView>();
            if (route != null)
                route.Redirect();
            else
                throw new RouteNotRegisteredException(typeof(TView));
        }

        public static void RedirectTo<TView>(params KeyValuePair<string, string>[] parameterValues) where TView : IBaseView
        {
            // TODO Implement RedirectTo<TView>
            throw new NotImplementedException("RedirectTo with parameters not implemented.");
        }
    }
}
